﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using Topro.Db;
using Topro.Entity.Tables;

namespace Topro.Admin.Controllers
{
    /// <summary>
    /// 导入
    /// </summary>
    public class ImportController : Controller
    {
        #region 注入
        /// <summary>
        /// 
        /// </summary>
        private readonly IWebHostEnvironment _hostEnvironment;

        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="authService">IQS接口</param>
        public ImportController(IWebHostEnvironment hostEnvironment, IDb db)
        {
            _hostEnvironment = hostEnvironment;
            _db = db;
        }
        #endregion

        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string ConvertString(object obj)
        {

            try
            {
                if(obj != null)
                {
                    return obj.ToString();
                }
                else
                {
                    return "";
                }
            }
            catch(Exception ex)
            {
                return "";
            }
        }

        public IActionResult Index()
        {
            try
            {
                throw new Exception("");

                //文件名称
                var fileName = @$"D:\news.xlsx";
                //路径
                var filePath = Path.Combine(@$"{_hostEnvironment.WebRootPath}", fileName);

                FileInfo file = new FileInfo(fileName);
                //是否存在
                if (!file.Exists)
                {
                    return Content("文件不存在.");
                }
                //指定EPPlus使用非商业证书
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                using (ExcelPackage package = new ExcelPackage(file))
                {
                    //get the first worksheet in the workbook
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                    //获取worksheet的行数
                    int rows = worksheet.Dimension.End.Row;
                    //获取worksheet的列数
                    int cols = worksheet.Dimension.End.Column;


                    var configs = new List<Config>();

                    var itemNo = "";
                    var cycleNo = "";

                    for (int i =1; i<= rows;i++)
                    {
                        var config = new Config();


                        config.Type = 40;
                        //料号
                        var partNo = ConvertString(worksheet.Cells[i, 1].Value);
                        if(!string.IsNullOrEmpty(partNo))
                        {
                            config.PartNo = itemNo = partNo;
                        }
                        else
                        {
                            config.PartNo = itemNo;
                        }

                        config.LotNo = "";
                        // 叠合次数号
                        var cycle = ConvertString(worksheet.Cells[i, 2].Value);
                        if (!string.IsNullOrEmpty(cycle))
                        {
                            config.Cycle = cycleNo = cycle;
                        }
                        else
                        {
                            config.Cycle = cycleNo;
                        }

                        config.FieldType = 0;

                        //值
                        var value = ConvertString(worksheet.Cells[i, 3].Value);
                        if (!string.IsNullOrEmpty(value))
                        {
                            config.Value = @$"<p>{value}</p>";
                        }
                        config.Status = 1;
                        config.CreatedBy = 1;
                        config.CreatedDate = DateTime.Now;

                        var model = _db.DbConnection.Query<Config>("select * from config where PartNo=@PartNo and Cycle=@Cycle", new { PartNo = config.PartNo, Cycle=config.Cycle }).FirstOrDefault();
                        if (model != null)
                        {
                            model.Value += @$"<p>{config.Value}</p>";
                            _db.DbConnection.Update<Config>(model);
                        }
                        else
                        {
                            var id = (int)_db.DbConnection.Insert<Config>(config);
                        }
                        
                    }

                    var xx = configs;
                }
                return Content("成功.");
            }
            catch(Exception ex)
            {
                return Content(ex.Message);
            }
        }
    }
}
